<!DOCTYPE html>
<%@page contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
 <html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>  
<body>    
   <br/><input id="text" type="text"/>
    <button onclick="send()">发送消息</button>
    <hr/>
    <div id="message"></div>
</body>

<script type="text/javascript">
    var websocket = null;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:8080/webSocketTest/websocket/test?sid=aaaa");
    }else if ('MozWebSocket' in window) {  
        ws = new MozWebSocket(target);  
    } else {  
        alert('浏览器不支持WebSocket');  
    }  

    //连接发生错误的回调方法
    websocket.onerror = function () {
        setMessageInnerHTML("WebSocket连接发生错误");
    };

    //连接成功建立的回调方法
    websocket.onopen = function () {
        setMessageInnerHTML("WebSocket连接成功");
    }

    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        setMessageInnerHTML(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function (event) {
    		//如果服务器挂掉,重新连接其它服务器
		if(event.code==1006){
			location.href='http://localhost:8081/webSocketTest/TestWebSocket.jsp';
		}
    }
 
    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //关闭WebSocket连接
    function closeWebSocket() {
        websocket.close();
    }

    //发送消息
    function send() {
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>
</html>